export class WebSocketUtil {
  constructor(url, heartBeat) {
    this.url = url;
    this.websocket = null;
    this.openFn = new Function();
    this.messageFn = new Function();
    this.closeFn = new Function();
    this.errorFn = new Function();
    this.doneFn = new Function();
    this.heartBeat = heartBeat || false;
    this.layerFn = new Function();
    this.heartCheck = new heartCheck();
    this.initWebSocket();
  }

  initWebSocket() {
    if ("WebSocket" in window) {
      console.log("sdfsdf");
      this.websocket = new WebSocket(this.url);
      //设置心跳
      if (this.heartBeat) {
        this.heartCheck.WebSocketUtil = this;
      }
      this.handleWebSocket();
    } else {
      console.error("不支持WebSocket");
    }
  }

  handleWebSocket() {
    const that = this;
    that.websocket.onopen = (event) => {
      window.TestWs = this;
      that.openFn(event);
      // 是否心跳
      if (that.heartBeat) {
        that.heartCheck.start();
      }
    };
    that.websocket.onmessage = (event) => {
      if (that.heartBeat) {
        that.heartCheck.start();
      }
      that.messageFn(event);
    };
    that.websocket.onclose = (event) => {
      that.closeFn(event);
      that.doneFn(event);
    };
    that.websocket.onerror = (event) => {
      that.errorFn(event);
    };
  }

  send(msg) {
    this.websocket.send(msg);
  }
  close(enable) {
    this.websocket.close();
    console.log("关闭");
    if (enable) {
      this.heartCheck.reset();
    }
  }
}

// 心跳对象
class heartCheck {
  constructor() {
    this.enable = true;
    this.heartLoadTime = 1000 * 10;
    this.heartTimer = null;
    this.reconnectLoadTime = 1000 * 10;
    this.reconnectTimer = null;
    this.reconnectCount = 0;
    this.reconnectMaxCount = 10;
    this.WebSocketUtil = null;
    this.heartMessage = JSON.stringify({
      flag: "HEARTBEAT",
    });
  }
  reset() {
    clearTimeout(this.heartTimer);
    clearTimeout(this.reconnectTimer);
    this.heartTimer = null;
    this.reconnectTimer = null;
  }
  start() {
    const that = this;
    this.reset();
    this.heartTimer && clearTimeout(this.heartTimer);
    this.heartTimer = setTimeout(() => {
      //发送心跳
      that.WebSocketUtil.send(this.heartMessage);
      //延迟重连
      that.reconnect();
    }, this.heartLoadTime);
  }
  reconnect() {
    const that = this;
    this.reconnectTimer && clearTimeout(this.reconnectTimer);
    this.reconnectTimer = setTimeout(() => {
      //判断是否关闭ws
      that.WebSocketUtil.close();
      //重连次数过多提示
      if (that.reconnectCount > that.reconnectMaxCount) {
        //提示错误
        //执行收尾工作
        that.WebSocketUtil.layerFn();
        return;
      }
      //重连次数累计
      that.reconnectCount++;
      //重新连接
      that.WebSocketUtil.initWebSocket();
      //延迟重连
      that.reconnect();
    }, this.reconnectLoadTime);
  }
}
